package com.guobox.movies.view.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.guobox.movies.R;
import com.guobox.movies.entity.NasEntity;
import com.guobox.movies.nasManager.NasIpCallback;
import com.guobox.movies.nasManager.NasManager;
import com.guobox.movies.utils.httpsutils.OkhttpsUtils;

import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by xuxinlei on 2018/1/3.
 */

public abstract class BaseActivity extends Activity implements NasIpCallback {
    private static final String TAG = BaseActivity.class.getSimpleName();
    Context context = this;
    NasManager nasManager;
    MaterialDialog searchDialog;
    MaterialDialog searchProgress;
    Timer searchTimer = new Timer();
    String ip = "";

    public abstract void initConnection(String ip);

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    void checkNasConnection() {
        nasManager = new NasManager(this);
        nasManager.addNasIpCallback(this);
        new Thread() {
            @Override
            public void run() {
                final NasEntity nasEntity = nasManager.getNas();
                if (nasEntity != null && !TextUtils.isEmpty(nasEntity.getNasIp())) {
                    try {
                        Response response = OkhttpsUtils.getCheckOkHttpClient().newCall(new Request.Builder().url("http://" + nasEntity.getNasIp() + "/application/setting/testsate ")
                                .build()).execute();
                        String resString = response.body().string();
                        if (resString.contains("teststateok")) {
                            Log.i(TAG, resString);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    initConnection(nasEntity.getNasIp());
                                }
                            });

                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    showSearchAlert();
                                    initConnection(null);
                                }
                            });

                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showSearchAlert();
                                initConnection(null);
                            }
                        });


                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showSearchAlert();
                            initConnection(null);
                        }
                    });
                }
            }
        }.start();
    }


    @Override
    public void onNasIpCallback(final String ip) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (searchProgress != null && searchProgress.isShowing()) {
                    initConnection(nasManager.getNas().getNasIp());
                    searchProgress.dismiss();
                    Toast.makeText(context, "搜索完成,已连接至" + ip, Toast.LENGTH_SHORT).show();
                    if (searchTimer != null) {
                        searchTimer.cancel();
                    }
                }
            }
        });
    }

    @Override
    public void beforeSearchNas() {
        if (searchProgress != null && !searchProgress.isShowing()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    searchProgress.show();
                    searchTimer.cancel();
                    searchTimer = new Timer();
                    searchTimer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            Response response = null;
                            try {
                                response = OkhttpsUtils.getCheckOkHttpClient().newCall(new Request.Builder().url("http://" + nasManager.getNas().getNasIp() + "/application/setting/testsate ")
                                        .build()).execute();
                                if (response.body().string().contains("teststateok")) {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    if (searchProgress.isShowing()) {
                                                        searchProgress.dismiss();
                                                        initConnection(nasManager.getNas().getNasIp());
                                                        Toast.makeText(context, "已连接至设备！", Toast.LENGTH_SHORT).show();
                                                    }
                                                }
                                            });
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (searchProgress.isShowing()) {
                                            searchProgress.dismiss();
                                            Toast.makeText(context, "未发现设备！", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }

                        }
                    }, 5000);
                }
            });
        }
    }

    protected void showSearchAlert() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                searchDialog = new MaterialDialog.Builder(BaseActivity.this)
                        .title("提示")
                        .content("未发现NAS，是否重新搜索？")
                        .theme(Theme.DARK)
                        .buttonRippleColorRes(R.color.white)
                        .positiveText("搜索")
                        .negativeText("取消")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                nasManager.searchNas();
                            }
                        }).positiveFocus(true).build();
                try {
                    searchDialog.show();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        nasManager.unRegister();
        super.onDestroy();
    }
}
